import React from 'react';
import { Paper, Box, Typography, Divider, Button, CircularProgress } from '@mui/material';
import { LogViewer } from 'utils/use-server';
import useMlsFormSubmissionComplete from './use-mls-form-submission-complete';
import {
  MLS_DB_HOST,
  MLS_DB_NAME,
  MLS_DB_TABLE,
  MLS_DB_USERNAME,
  MLS_DB_PASSWORD
} from 'config/index';

// Import icon components
import HomeIcon from '@mui/icons-material/Home';
import PhotoCameraIcon from '@mui/icons-material/PhotoCamera';
import FlashOnIcon from '@mui/icons-material/FlashOn';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import PriceCheckIcon from '@mui/icons-material/PriceCheck';

// Import all section components
import ContactSection from 'components/ui/ContactSection';
import PersonalSection from 'components/ui/PersonalSection';
import OwnerSection from 'components/ui/OwnerSection';
import PropertySection from 'components/ui/PropertySection';
import AdditionalSection from 'components/ui/AdditionalSection';
import { DEFAULT_HOW_OPTIONS, STATES, COUNTRIES } from 'components/ui/Constants';
import SequentialBackgroundIcons from 'components/electrons/SequentialBackgroundIcons';

/**
 * Enhanced MLS Form Component with section control and complete field support
 */
const MLSFormComponentCompleteOrdered = ({ 
  useBorder = true, 
  useColor = '#ffffff', 
  useSize = 'small', 
  useButtonSize = 'medium',
  useMiddle = false,
  showLogViewer = false,
  defaultSameAddress = false, // Controls whether address toggle is set by default
  sectionOrder = ['contact', 'personal', 'owner', 'property', 'additional'], // Controls section ordering
  howOptions = DEFAULT_HOW_OPTIONS, // Configurable "How did you hear about us" options
  showBackgroundIcons = true // Controls whether to show the sequential background icons
}) => {
  const [formData, setFormData] = React.useState({
    // Contact Information
    cEmail: '',
    cPhone: '',
    cFax: '',
    cHow: howOptions[0], // Default to first option

    // Personal Information
    cBillFname: '',
    cBillLname: '',
    cBillCompany: '',
    
    // Owner Address
    cBillAddress1: '',
    cBillAddress2: '',
    cBillCity: '',
    cBillState: '',
    cBillZip: '',
    bill_county: '',
    cBillCountry: 'USA',
    
    // Same Address Toggle
    billEqualShip: defaultSameAddress ? 'Y' : 'N',
    
    // Property Information
    cShipCompany: '',
    cShipFname: '',
    cShipLname: '',
    cShipAddress1: '',
    cShipAddress2: '',
    cShipCity: '',
    cShipState: '',
    cShipZip: '',
    ship_county: '',
    cShipCountry: 'USA',
    
    // Additional Information
    cMemo: '',
    cPass: '',
    cPassHint: '',
    cWholesaleDiscount: null
  });

  // Define the background icons to use
  const backgroundIcons = [
    HomeIcon,
    PhotoCameraIcon,
    FlashOnIcon,
    AccountBalanceIcon,
    PriceCheckIcon
  ];

  const [errors, setErrors] = React.useState({});
  const { submitForm, submitting, submitSuccess, resetSubmission } = useMlsFormSubmissionComplete({
    dbHost: MLS_DB_HOST,
    dbName: MLS_DB_NAME,
    dbTable: MLS_DB_TABLE,
    dbUsername: MLS_DB_USERNAME,
    dbPassword: MLS_DB_PASSWORD
  });

  React.useEffect(() => {
    // Initialize the form with the default same address setting
    if (defaultSameAddress) {
      setFormData(prevData => ({
        ...prevData,
        billEqualShip: 'Y'
      }));
    } else {
      setFormData(prevData => ({
        ...prevData,
        billEqualShip: 'N'
      }));
    }
  }, [defaultSameAddress]);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prevData => ({
      ...prevData,
      [name]: type === 'checkbox' ? (checked ? 'Y' : 'N') : value
    }));

    // If shipping address is same as billing, update shipping fields
    if (name === 'billEqualShip' && checked) {
      setFormData(prevData => ({
        ...prevData,
        cShipAddress1: prevData.cBillAddress1,
        cShipAddress2: prevData.cBillAddress2,
        cShipCity: prevData.cBillCity,
        cShipState: prevData.cBillState,
        cShipZip: prevData.cBillZip,
        ship_county: prevData.bill_county,
        cShipCountry: prevData.cBillCountry,
        cShipFname: prevData.cBillFname,
        cShipLname: prevData.cBillLname,
        cShipCompany: prevData.cBillCompany
      }));
    }

    // Clear error for this field if any
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const validate = () => {
    const newErrors = {};
    
    // Required fields validation
    // Contact Information
    if (!formData.cEmail) {
      newErrors.cEmail = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.cEmail)) {
      newErrors.cEmail = 'Email is invalid';
    }
    if (!formData.cPhone) newErrors.cPhone = 'Phone number is required';
    if (!formData.cHow) newErrors.cHow = 'Please select how you heard about us';
    
    // Personal Information
    if (!formData.cBillFname) newErrors.cBillFname = 'First name is required';
    if (!formData.cBillLname) newErrors.cBillLname = 'Last name is required';
    
    // Owner Address
    if (!formData.cBillAddress1) newErrors.cBillAddress1 = 'Address is required';
    if (!formData.cBillCity) newErrors.cBillCity = 'City is required';
    if (!formData.cBillState) newErrors.cBillState = 'State is required';
    if (!formData.cBillZip) newErrors.cBillZip = 'ZIP code is required';
    
    // If not using same address for property, validate property address fields
    if (formData.billEqualShip === 'N') {
      if (!formData.cShipFname) newErrors.cShipFname = 'Property owner first name is required';
      if (!formData.cShipLname) newErrors.cShipLname = 'Property owner last name is required';
      if (!formData.cShipAddress1) newErrors.cShipAddress1 = 'Property address is required';
      if (!formData.cShipCity) newErrors.cShipCity = 'Property city is required';
      if (!formData.cShipState) newErrors.cShipState = 'Property state is required';
      if (!formData.cShipZip) newErrors.cShipZip = 'Property ZIP code is required';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    
    if (validate()) {
      console.log('Form data submitted:', formData);
      
      // Submit the form using our hook
      submitForm(formData).then(success => {
        if (success) {
          // Reset form after submission
          setFormData({
            cEmail: '',
            cPhone: '',
            cFax: '',
            cHow: howOptions[0],
            cBillFname: '',
            cBillLname: '',
            cBillCompany: '',
            cBillAddress1: '',
            cBillAddress2: '',
            cBillCity: '',
            cBillState: '',
            cBillZip: '',
            bill_county: '',
            cBillCountry: 'USA',
            billEqualShip: defaultSameAddress ? 'Y' : 'N',
            cShipCompany: '',
            cShipFname: '',
            cShipLname: '',
            cShipAddress1: '',
            cShipAddress2: '',
            cShipCity: '',
            cShipState: '',
            cShipZip: '',
            ship_county: '',
            cShipCountry: 'USA',
            cMemo: '',
            cPass: '',
            cPassHint: '',
            cWholesaleDiscount: null
          });
        }
      });
    } else {
      console.log('Form has errors:', errors);
    }
  };

  // Style configurations based on props
  const textFieldStyle = {
    backgroundColor: useColor,
    '& .MuiOutlinedInput-root': {
      '& fieldset': {
        borderColor: useBorder ? 'rgba(0, 0, 0, 0.23)' : 'transparent',
      },
    },
    marginBottom: '8px',
  };

  const formContainerStyle = {
    textAlign: useMiddle ? 'center' : 'left',
    padding: 3,
    borderRadius: 2,
    boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
    backgroundColor: '#ffffff',
    position: 'relative',
    overflow: 'hidden', // Ensure icons don't overflow the Paper
  };

  const sectionHeaderStyle = {
    fontSize: '0.9rem',
    fontWeight: 'bold',
    marginBottom: '8px',
    marginTop: '16px',
    color: 'primary.main',
    position: 'relative', // To stay above background icons
    zIndex: 2,
  };

  // Render the correct sections based on section order
  const renderSection = (section) => {
    const sectionProps = {
      formData,
      handleChange,
      errors,
      textFieldStyle,
      sectionHeaderStyle,
      useSize,
      howOptions,
    };

    switch(section) {
      case 'contact':
        return <ContactSection key="contact" {...sectionProps} />;
      case 'personal':
        return <PersonalSection key="personal" {...sectionProps} />;
      case 'owner':
        return <OwnerSection key="owner" {...sectionProps} />;
      case 'property':
        return <PropertySection key="property" {...sectionProps} />;
      case 'additional':
        return <AdditionalSection key="additional" {...sectionProps} />;
      default:
        return null;
    }
  };

  return (
    <Paper sx={formContainerStyle} elevation={3}>
      {showLogViewer && (
        <Box sx={{ mb: 3 }}>
          <LogViewer 
            maxHeight="200px" 
            showTimestamp={true}
            showLevel={true}
            showData={true}
            maxItems={50}
          />
        </Box>
      )}
      
      {!submitSuccess ? (
        <form onSubmit={handleSubmit}>
          <Typography variant="h6" sx={{ 
            fontSize: '1.1rem', 
            fontWeight: 'bold', 
            mb: 2, 
            textAlign: 'center', 
            color: 'primary.main',
            position: 'relative',
            zIndex: 2
          }}>
            Kickstart Your Commission-Free Home Sale
          </Typography>
          
          <Divider sx={{ mb: 2, position: 'relative', zIndex: 2 }} />
          
          {/* Background Icons Component - placed inside the paper after the Typography and Divider */}
          {showBackgroundIcons && (
            <Box sx={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 9999 }}>
              <SequentialBackgroundIcons 
                icons={backgroundIcons}
                opacity={0.08}
                color="#1976d2"
                maxWidth="500px"
              />
            </Box>
          )}
          
          {/* Form sections with z-index to appear above the background icons */}
          <Box sx={{ position: 'relative', zIndex: 10000 }}>
            {sectionOrder.map((section, index) => (
              <React.Fragment key={section}>
                {renderSection(section)}
                {index < sectionOrder.length - 1 && <Divider sx={{ my: 2 }} />}
              </React.Fragment>
            ))}
          </Box>
          
          <Box sx={{ mt: 3, textAlign: 'center', position: 'relative', zIndex: 2 }}>
            <Button 
              type="submit" 
              variant="contained" 
              color="primary" 
              size={useButtonSize}
              disabled={submitting}
              sx={{ 
                fontWeight: 'bold', 
                px: 4,
                py: 1.5,
                borderRadius: '4px',
                fontSize: '0.9rem'
              }}
            >
              {submitting ? (
                <>
                  <CircularProgress size={20} color="inherit" sx={{ mr: 1 }} />
                  SUBMITTING...
                </>
              ) : (
                'MAXIMIZE MY LISTING PROFIT NOW'
              )}
            </Button>
            <Typography sx={{ fontSize: '0.7rem', mt: 1, color: '#666' }}>
              By submitting, you agree to our Terms of Service and Privacy Policy
            </Typography>
          </Box>
        </form>
      ) : (
        <Box sx={{ textAlign: 'center', py: 4, position: 'relative', zIndex: 2 }}>
          <Typography variant="h6" sx={{ color: '#2e7d32', mb: 2 }}>
            Thank You for Your Submission!
          </Typography>
          <Typography variant="body2">
            We've received your information and a member of our team will contact you shortly to discuss your flat-fee MLS listing.
          </Typography>
          <Button 
            variant="outlined" 
            color="primary"
            size={useButtonSize}
            sx={{ mt: 3 }}
            onClick={() => resetSubmission()}
          >
            Submit Another Property
          </Button>
        </Box>
      )}
    </Paper>
  );
};

export default MLSFormComponentCompleteOrdered;